package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.service.impl.UserServiceImpl;
import org.geektimes.web.mvc.controller.ModelAndView;
import org.geektimes.web.mvc.controller.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

public class RegisterController implements RestController {
    UserService userService = new UserServiceImpl();
    private AtomicLong id = new AtomicLong(-1);

    @POST
    @Path("/register")
    public ModelAndView register(User user) {
        user.setId(id.addAndGet(1));
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        // 校验结果
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error.jsp");
        Map<String,List> data = new Hashtable<>();
        if(!violations.isEmpty()) {
            //校验没有通过
            List<String> messages = violations.stream().map(c -> c.getMessage()).collect(Collectors.toList());
            data.put("messages",messages);
            mv.setModel(data);
            return mv;
        }
        User user1 = userService.queryUserByNameAndPassword(user.getName(), user.getPassword());
        if (null == user1 && userService.register(user)) {
            mv.setViewName("success.jsp");
            return mv;
        }
        //用户名和密码已存在
        List<String> list = new ArrayList<>();
        list.add("用户名和密码已存在");
        data.put("messages",list);
        mv.setModel(data);
        return mv;
    }
}
